<?php

namespace app\controller;

use app\BaseController;
use app\model\SysUploadFiles;
use think\helper\Str;
use think\Response;

class Upload extends BaseController
{
    public function images(): Response
    {
        $file = request()->file('images');
        if (empty($file)) throw new \Exception("请选择图片", 7001);
        $lastName = $file->getOriginalName();
        $fileName = md5(time() . Str::random(8)) . '.' . $file->extension();
        $size = $file->getSize();
        $ext = $file->extension();
        $dir = "./upload/images/" . date("Ymd");
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $url = $this->request->domain() . trim($dir, '.') . "/$fileName";
        $file->move($dir, $fileName);
        $dir = "$dir/$fileName";
        //存储文件信息
        $this->app->make(SysUploadFiles::class)->save([
            'name' => $lastName,
            'url' => $url,
            'size' => $size,
            'ext' => $ext,
            'dir' => $dir
        ]);
        return $this->success(['url' => $url]);
    }
}
